package com.zznzzn.androidshixun0826;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class NewContactActivity extends AppCompatActivity {

    private ImageView new_img;
    private EditText new_name,new_phone,new_address;
    private Button new_yes,new_no;
    private View.OnClickListener newbtnlistener;
    private int imgid = 0;
    private File moutPutFile;
    private Bitmap mbm;

    private final int REQUEST_CODE_TAKE_PHOTO = 101;
    private final int REQUEST_CODE_CLIP_PHOTO = 102;
    private final int REQUEST_CODE_LOAD_PHOTO = 103;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_contact);
        setTitle("新建联系人");

        new_img = findViewById(R.id.new_img);
        new_name = findViewById(R.id.new_name);
        new_phone = findViewById(R.id.new_phone);
        new_address = findViewById(R.id.new_address);
        new_yes = findViewById(R.id.new_yes);
        new_no = findViewById(R.id.new_no);

        new_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //单击进入拍照页面
                if (hasCam()){
                    takePhoto();
                }else {
                    return;
                }
            }
        });

        new_img.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                //打开相册intent
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent,REQUEST_CODE_LOAD_PHOTO);
                return true;
            }
        });

        newbtnlistener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.new_yes:submit();break;
                    case R.id.new_no:cancel();break;
                    default:break;
                }
            }
        };

        new_yes.setOnClickListener(newbtnlistener);
        new_no.setOnClickListener(newbtnlistener);

        if (savedInstanceState != null){

            Contact ct = (Contact) savedInstanceState.getSerializable("store_contact");
            if (ct != null){
                new_name.setText(ct.getName());
                new_phone.setText(ct.getPhone());
                new_address.setText(ct.getAddress());
                new_img.setImageBitmap(BitmapFactory.decodeByteArray(ct.getPhoto(),0,ct.getPhoto().length));
            }

        }

    }



    private byte[] bmtobt(Bitmap bm){
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG,100,bos);
        return bos.toByteArray();
    }

    public void submit(){
        String name = new_name.getText().toString();
        String phone = new_phone.getText().toString();
        String address = new_address.getText().toString();
        Contact xiaoming = new Contact(name,phone,address,bmtobt(mbm));


        Intent intent = new Intent();
        intent.putExtra("contact",xiaoming);
        setResult(200,intent);
        finish();
    }

    public void cancel(){
        setResult(502);
        finish();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        String name = new_name.getText().toString();
        String phone = new_phone.getText().toString();
        String address = new_address.getText().toString();
        byte[] bt = {};
        if (mbm != null) {
            bt = bmtobt(mbm);
        }
        Contact ct = new Contact(name,phone,address,bt);
        outState.putSerializable("store_contact",ct);
        super.onSaveInstanceState(outState);
    }

    private boolean hasCam(){
        PackageManager pm = getPackageManager();
        if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA) && !pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)){
            Toast.makeText(this,"no camara found",Toast.LENGTH_SHORT).show();
            return false;
        }else{
            return true;
        }
    }

    private void takePhoto(){
        String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        moutPutFile = new File(sdPath,System.currentTimeMillis()+".tmp");
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24){
            uri = FileProvider.getUriForFile(this,getApplicationContext().getPackageName()+".provider",moutPutFile);
        }else{
            uri  = Uri.fromFile(moutPutFile);
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.Images.Media.ORIENTATION,0);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
        startActivityForResult(intent,REQUEST_CODE_TAKE_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_TAKE_PHOTO){
            onTakePhotoFinished(resultCode,data);
        }else if(requestCode == REQUEST_CODE_CLIP_PHOTO){
            onClipPhotoFinished(resultCode,data);
        }else if (requestCode == REQUEST_CODE_LOAD_PHOTO){
            onSelectPhotoFinished(resultCode,data);
        }
    }

    private void onSelectPhotoFinished(int resultCode, Intent data) {
        //从相册中选取到的图片，还是用系统裁切
        if (resultCode == RESULT_CANCELED){
            Toast.makeText(this,"select photo canceled",Toast.LENGTH_SHORT).show();
        }else if (resultCode == RESULT_OK && data != null){
            Uri selected = data.getData();
            Log.d("===selected==", String.valueOf(selected));
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selected,filePathColumn,null,null,null);
            cursor.moveToFirst();
            int index = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(index);
            cursor.close();

            moutPutFile = new File(picturePath);
            clipPhoto(selected);
        }
    }

    private void onClipPhotoFinished(int resultCode, Intent data) {
        if (resultCode == RESULT_CANCELED){
            Toast.makeText(this,"clip photo canceled",Toast.LENGTH_SHORT).show();
        }else if(resultCode != RESULT_OK){
            Toast.makeText(this,"clip photo failed",Toast.LENGTH_SHORT).show();
        }else {
            //显示裁切后图片
            mbm = BitmapFactory.decodeFile(moutPutFile.getAbsolutePath()+"tmp");
            new_img.setImageBitmap(mbm);
        }
    }

    private void onTakePhotoFinished(int resultCode, Intent data) {
        // 拍照成功
        if (resultCode == RESULT_CANCELED){
            Toast.makeText(this,"take photo canceled",Toast.LENGTH_SHORT).show();
        }else if (resultCode != RESULT_OK){
            Toast.makeText(this,"take photo failed",Toast.LENGTH_SHORT).show();
        }else{
            clipPhoto(Uri.fromFile(moutPutFile));
        }
    }

    private void clipPhoto(Uri uri) {
        //调用系统自带的裁剪工具
        Log.d("====from uri==",uri.toString());

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri,"image/*");
        intent.putExtra("crop","true");
        intent.putExtra("aspectX",1);
        intent.putExtra("aspectY",1);
        intent.putExtra("outputX",300);
        intent.putExtra("outputY",300);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(moutPutFile.getAbsoluteFile() + "tmp")));
        startActivityForResult(intent,REQUEST_CODE_CLIP_PHOTO);
    }
}















